package dao

import (
	"context"
	"mini-app/internal/dal"
	"mini-app/internal/models"
	"time"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type ShoppingCart struct{}

func (ShoppingCart) Detail(ctx context.Context, query *dal.Query, openid, robotName, goodsID string) (
	res *models.ShoppingCart, err error,
) {
	if openid == "" {
		err = errorx.New("用户不能为空", -1)
		return
	}
	if robotName == "" {
		err = errorx.New("机器不能为空", -1)
		return
	}
	if goodsID == "" {
		err = errorx.New("商品不能为空", -1)
		return
	}
	sc := query.ShoppingCart
	res, err = sc.WithContext(ctx).
		Where(sc.Openid.Eq(openid)).
		Where(sc.RobotName.Eq(robotName)).
		Where(sc.GoodsID.Eq(goodsID)).
		Take()
	return
}

func (ShoppingCart) Create(ctx context.Context, query *dal.Query, openid, robotName, goodsID string, count int) (err error) {
	sc := query.ShoppingCart
	d := models.ShoppingCart{}
	d.ID, _ = helper.UUID{}.String()
	d.Openid = openid
	d.RobotName = robotName
	d.GoodsID = goodsID
	d.Count = count
	d.CreatedAt = time.Now().Unix()
	sc.WithContext(ctx).Create(&d)
	return
}

func (ShoppingCart) Save(ctx context.Context, query *dal.Query, openid, robotName, goodsID string, count int) (err error) {
	sc := query.ShoppingCart
	tx := sc.WithContext(ctx)
	tx.Where(sc.Openid.Eq(openid)).
		Where(sc.RobotName.Eq(robotName)).
		Where(sc.GoodsID.Eq(goodsID)).
		Updates(map[string]interface{}{
			"count": count,
		})
	return
}
func (ShoppingCart) Reduce(ctx context.Context, query *dal.Query, openid, robotName, goodsID string, count int) (err error) {
	sc := query.ShoppingCart
	tx := sc.WithContext(ctx)
	tx.Where(sc.Openid.Eq(openid)).
		Where(sc.RobotName.Eq(robotName)).
		Where(sc.GoodsID.Eq(goodsID)).
		Where(sc.Count.Gte(count)).
		UpdateColumn(sc.Count, gorm.Expr("count - ?", count))
	return
}

func (ShoppingCart) List(ctx context.Context, query *dal.Query, openid string) (
	res []*models.ShoppingCart, err error,
) {
	if openid == "" {
		err = errorx.New("用户不能为空", -1)
		return
	}
	sc := query.ShoppingCart
	res, err = sc.WithContext(ctx).
		Where(sc.Openid.Eq(openid)).
		Where(sc.Count.Neq(0)).
		Find()
	return
}

func (ShoppingCart) Delete(ctx context.Context, query *dal.Query, openid, robotName, goodsID string) (err error) {
	if openid == "" {
		err = errorx.New("用户不能为空", -1)
		return
	}
	if robotName == "" {
		err = errorx.New("机器不能为空", -1)
		return
	}
	if goodsID == "" {
		err = errorx.New("商品不能为空", -1)
		return
	}
	sc := query.ShoppingCart
	sc.WithContext(ctx).
		Where(sc.Openid.Eq(openid)).
		Where(sc.RobotName.Eq(robotName)).
		Where(sc.GoodsID.Eq(goodsID)).
		Delete()
	return
}
